package com.example.project.api.service;

import com.example.project.api.dto.GiftDTO;
import com.example.project.api.mapper.TbWinMapper;
import com.example.project.api.model.TbBox;
import com.example.project.api.model.TbWin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.project.api.mapper.TbBoxMapper;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author: Jerry.Zhang
 * @date: 2022/9/22 14:02
 */
@Service
public class TbBoxService extends ServiceImpl<TbBoxMapper, TbBox> {

    @Autowired
    private TbBoxMapper tbBoxMapper;
    @Autowired
    private TbWinMapper tbWinMapper;

    /**
     * 获取盲盒
     *
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public GiftDTO getBox(String ip) {
        List<GiftDTO> giftList = new ArrayList<>();
        Integer sum = 0;
        List<TbBox> tbBoxList = tbBoxMapper.selectList(null);
        for (TbBox tbBox : tbBoxList) {
            if (tbBox.getGoodNum() > 0) {
                for (int i = 0; i < tbBox.getGoodNum(); i++) {
                    GiftDTO giftDTO = new GiftDTO();
                    giftDTO.setId(tbBox.getId());
                    giftDTO.setName(tbBox.getGoodName());
                    giftDTO.setPrice(tbBox.getGoodPrice());
                    giftList.add(giftDTO);
                }
            }
            sum += tbBox.getGoodNum();
        }
        if (sum == 0) {
            return null;
        }
        int random = new Random().nextInt(sum);
        GiftDTO giftDTO = giftList.get(random);
        TbBox tbBox = tbBoxMapper.selectById(giftDTO.getId());
        tbBox.setGoodNum(tbBox.getGoodNum() - 1);
        tbBoxMapper.updateById(tbBox);
        TbWin win = new TbWin();
        win.setBoxId(giftDTO.getId());
        win.setBoxDate(LocalDateTime.now());
        win.setUserIp(ip);
        tbWinMapper.insert(win);
        return giftDTO;
    }

}
